import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { storage } from "@/utils/storage"
import { ElMessage } from 'element-plus'

const info = storage.get('info') as { token: string };
// 本地环境
const env = "local"; // local dev
export let BASEURL = ""; // 部署环境
export let assetsUrl = ""; // 资源


/* 静态资源路劲
*   本地访问路径和build后的路劲不一样
    本地的是 ../../../src/assets
    build后的路劲是 ./assets 或者写 /assets 也可以
*/

if (env === "local") {
	assetsUrl = "../../../src/assets";
  BASEURL = "http://im03.powerup.ifun.com:8899";

} else if (env === "dev") {
	assetsUrl = "./assets";
  BASEURL = "http://im03.powerup.ifun.com:8899";
}

// 创建 axios 实例
const service = axios.create({
  // baseURL: import.meta.env.VITE_APP_BASE_API,
  baseURL: BASEURL,
  timeout: 50000,
  headers: { 
    // 'Authorization': info.token,
    'Content-Type': "application/x-www-form-urlencoded"
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    
    // const { token } = storage.get('info');
    if (info.token) {
      config.headers['Authorization'] = info.token;
    }
    // config.headers['Content-Type'] = "application/x-www-form-urlencoded"
    // console.log(config)
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, msg } = response.data;
    // console.log('响应拦截器', response.data);
    if (code === 200) {
      return response;
    } else {
      ElMessage.error(msg)
      // return response;
    }
    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer) {
      return response;
    }

    return Promise.reject(new Error(msg || "Error"));
  },
  (error: any) => {
    if (error.response.data) {
      const { code, msg } = error.response.data;
        console.log('error', msg);
      if (code === 500 || code === 502 || code === 504) {

      }
      // token 过期,重新登录

    }
    return Promise.reject(error.message);
  }
);

// // 导出 axios 实例
// export default service;
export const GET = (url: any, params: any) =>
  service({
    url,
    params,
  })
    .then((res) => Promise.resolve(res.data))
    .catch((err) => {
      console.log(err)
    });

export const POST = (url: any, data: any) =>
  service
    .post(url, data)
    .then((res) => Promise.resolve(res.data))
    .catch((err) => {
      console.log(err)
    });

export const PUT = (url: any, data: any) =>
  service
    .put(url, data)
    .then((res) => Promise.resolve(res.data))
    .catch((err) => {
      console.log(err)
    });

export const DELETE = (url: any, data: any) =>
  service
    .delete(url, data)
    .then((res) => Promise.resolve(res.data))
    .catch((err) => {
      console.log(err)
    });
